package cn.th.controller;


import cn.th.common.R;
import cn.th.entity.Admin;
import cn.th.service.IAdminService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author cn.th
 * @since 2024-03-30
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private IAdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public R<Map<String,Object>> login(@RequestBody Admin admin){
        log.info("提交的用户为：{}",admin);
        //登录空验证
        if (admin.getUsername()==null || admin.getPassword() ==null){
            return R.error("账号和密码不得为空");
        }

        //如果被禁用那么就不可以登录
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,admin.getUsername());
        //wrapper.eq(Admin::getPassword,admin.getPassword());
        Admin admin1 = adminService.getOne(wrapper);
        if (admin1 == null || passwordEncoder.matches(admin.getPassword(),admin1.getPassword())){
            return R.error(20002,"用户名或密码错误");
        }
        if (admin1.getStatus() == 0){
            return R.error( 20001,"该账号已被禁用");
        }
        Map<String,Object> data = adminService.login(admin1);
        if (data != null){
            log.info(data.toString());
            return R.success(data);
        }
        return null;
    }

    /**\
     * token验证传输个人信息
     * @param token
     * @return
     */
    @GetMapping("/info")
    public R<Map<String,Object>> info(String token){
        //根据token获取用户信息
        log.info("token:{}",token);

        Map<String,Object> data = adminService.getUserInfo(token);
        if (data != null){
            log.info("data:{}",data);
            return R.success(data);
        }
        return R.error(50014,"登录信息无效，请重新登录");
    }

//    /**
//     * 退出并清除token
//     * @param token
//     * @return
//     */
//    @PostMapping("/logout")
//    public R<?> logout(@RequestHeader("X-Token") String token){
//        adminService.logout(token);
//        return R.success();
//    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public R<?> logout(){
        return R.success();
    }

    /**
     * 新增管理员
     * @param admin
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Admin admin) {
        log.info("新增员工，员工信息：{}", admin.toString());

        //密码加密处理
        admin.setPassword(passwordEncoder.encode("123456"));
        //查询username，因为用户名唯一，如果用户名和其他人相同则返回error，状态码10000表示唯一性冲突
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,admin.getUsername());
        Long count = adminService.count(queryWrapper);
        log.info("count为：{}",count);
        if (count>0)
            return R.error(10000,"用户名重复，请重新设置");

        //admin.setPassword(passwordEncoder.encode(admin.getUsername()));
        adminService.save(admin);
        return R.success("新增员工成功");
    }

    /**
     * 查询管理员
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<Map<String,Object>> list(@RequestParam(value = "page") int page,
                                      @RequestParam(value = "pageSize") int pageSize,
                                      @RequestParam(value = "name", required = false) String name,
                                      @RequestParam(value = "username", required = false) String username,
                                      @RequestParam(value = "school", required = false) String school){
        Map<String,Object> data = adminService.queryAd(page, pageSize, name, username, school);

        return R.success(data);
    }

    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Admin admin) {
        log.info(admin.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id为: {}",id);

        adminService.updateById(admin);
        return R.success("员工信息更新成功");
    }

    /**
     * 修改管理员时页面的数据展示
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Admin> getAdminById(@PathVariable("id")Long id){
        Admin admin = adminService.getById(id);
        return R.success(admin);
    }

    /**
     * 删除管理员
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(String ids){
        adminService.removeBatchByIds(ids);
        return R.success("删除管理员成功");
    }
}
